<?php

declare(strict_types=1);

namespace app\api\controller\v1;

use app\api\model\UserCareProduct;
use app\api\model\UserHistory;
use app\common\Frontend;
use app\common\library\Broadcast;
use app\common\model\Customer;
use app\common\model\DistributionBrokerage;
use app\common\model\DistributionLog;
use app\common\model\Order;
use app\common\model\PublicStatus;
use app\common\model\User as ModelUser;
use app\common\model\UserMemberLog;
use app\common\model\UserMoneyLog;
use app\common\model\UserWithdrawal;
use general\Random;
use Godruoyi\Snowflake\Snowflake;
use think\facade\Cache;
use Throwable;
use think\Request;

class User extends Frontend
{
    use Broadcast;
    protected $model;
    protected $snowflake;
    protected array $allowFields = ['id', 'username', 'nickname', 'email', 'mobile', 'avatar', 'gender', 'birthday', 'money', 'score', 'join_time', 'motto', 'last_login_time', 'last_login_ip', 'user_type', 'recharge_time', 'expiration_time', 'membership_cycle', 'is_pay_password'];
    protected array $noNeedLogin = ['sendMobileCode', 'forgetPassword', 'userMenuList', 'helpCenterBtn','saveCustomer','verifyUserAuthCode'];

    public function initialize(): void
    {
        parent::initialize();
        $this->snowflake = new Snowflake();
        $this->model = new ModelUser();
    }

    //开通用户会员 -- 微信支付
    public function openedUserMember(): void
    {
        $order_no = date('YmdHis') . $this->snowflake->id();
        $data = $this->request->param();

        $row = $this->model->find($this->auth->id);
        if (!$row) {
            $this->error('未找到此用户');
        }

        //支付方式状态
        if (intval($data['pay_type']) === PublicStatus::PAY_TYPE_ONE) { //微信支付
            // 生成订单
            // 根据openid 获取用户id
            $this->payWx($row->id, $row->open_id, $order_no, $data['money'], '余额充值', '余额充值');
        } else {
            $UserMoneyLog = new UserMoneyLog();
            $result = false;
            $UserMoneyLog->startTrans();
            try {
                //余额支付开通会员处理业务逻辑
                $result =  UserMoneyLog::balancePayAfter($this->auth->id, $data['money'], PublicStatus::PAY_TYPE_ONE, '余额支付开通VIP');
                //支付之后扣钱
                // UserMoneyLog::payAfter($this->auth->id, $data['money'], '开通会员余额支付');
                $UserMoneyLog->commit();
            } catch (Throwable $e) {
                $UserMoneyLog->rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success('支付成功');
            } else {
                $this->error(('未知错误'));
            }
        }
    }
    //充值余额 -- 微信支付
    public function userRechargeBalance(): void
    {
        $order_sn = $this->request->param('order_sn');
        $order = Order::where(['order_sn' => $order_sn])->find();
        if (!$order) {
            $this->error('订单不存在');
        }
        //$order_no =  date('YmdHis') . $this->snowflake->id();
        $row = $this->model->find($this->auth->id);
        if (!$row) {
            $this->error('未找到此用户');
        }
        $this->payWx($row->id, $row->open_id, $order_sn, $order['pay_fee'], 'Q币充值', 'recharge');
    }

    //微信支付
    public function payWx($uid, $open_id, $order_no, $money, $desc, $attach)
    {
        // 生成订单
        // 根据openid 获取用户id
        $array_data = [
            'out_trade_no' => $order_no,
            'user_id' => $uid,
            'open_id' => $open_id,
            'total' => 1, //($money *PublicStatus::PUBLIC_ONE_HUNDRED),
            'currency' => 'CNY',
            'desc' => $desc,
            'attach' => $attach
        ];

        $result = false;

        $this->model->startTrans();
        if (true) {
            try {
                $result = $this->model->payWatch($array_data);
                $this->model->commit();
            } catch (Throwable $e) {
                $this->model->rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success('', [
                    'result' => $result
                ]);
            } else {
                $this->error(('未知错误'));
            }
        }
    }
    /**
     * 余额日志
     * @throws Throwable
     */
    public function balance()
    {
        $where = [];
        if ($this->request->has('type') && !empty($this->request->param('type'))) {
            $where[] = ['type', '=', $this->request->param('type')];
        }
        $where[] = ['user_id', '=', $this->auth->id];
        $limit      = $this->request->request('limit', 10);
        $moneyModel = new UserMoneyLog();
        $res        = $moneyModel->where($where)
            ->order('create_time desc')
            ->paginate($limit);

        $this->success('', [
            'list'  => $res->items(),
            'total' => $res->total(),
        ]);
    }
    /**
     * 会员充值日志
     * @throws Throwable
     */
    public function member()
    {
        $limit      = $this->request->request('limit', 10);
        $memberModel = new UserMemberLog();
        $res        = $memberModel->where('user_id', $this->auth->id)
            ->order('create_time desc')
            ->paginate($limit);

        $this->success('', [
            'list'  => $res->items(),
            'total' => $res->total(),
        ]);
    }



    //设置支付密码
    public function setPayPassword(): void
    {
        $row = $this->model->find($this->auth->id);
        if (!$row) {
            $this->error("当前用户未找到");
        }

        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error("参数不能为空");
            }

            $result = false;
            $this->model->startTrans();
            try {
                $result = $this->model->payPassword($row->id, $data['pay_password']);
                $this->model->commit();
            } catch (Throwable $e) {
                $this->model->rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success('successful', [
                    'list'  => $this->auth->getUserInfo()
                ]);
            } else {
                $this->error(('没有更新的行'));
            }
        }
    }

    //验证支付密码
    public function checkPayPassord(): void
    {
        $row = $this->model->find($this->auth->id);
        if (!$row) {
            $this->error("当前用户未找到");
        }
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error("参数不能为空");
            }
            $result = false;
            $this->model->startTrans();
            try {
                $result = $this->model->checkPayPassword($row->pay_password, $data['pay_password']);
                $this->model->commit();
            } catch (Throwable $e) {
                $this->model->rollback();
                $this->error($e->getMessage());
            }
            $this->success('successful', $result);
        }
    }

    //发送验证码
    public function sendMobileCode(): void
    {

        if ($this->request->isPost()) {
            $data = $this->request->post();
            $type = $this->request->post('type', 'other');
            if (!$data) {
                $this->error("参数不能为空");
            }
            if ($type !== 'mobile') {
                $row = $this->model->where(['mobile' => $data['mobile']])->find();
                if (!$row) {
                    $this->error("当前用户未找到");
                }
                $user_id = $row->id;
            }
            if ($type === 'mobile') {
                $isCkeckMobile = $this->model->checkMobile($data['mobile']);
                if ($isCkeckMobile) {
                    $this->error("手机号已经存在！");
                }
            }
            if ($this->auth->isLogin()) {
                $user_id = $this->auth->id;
            }
            //限制用户30秒内只能发送一次
            //获取第一次发送的信息
            $send_time = Cache::get($data['mobile'] . '-time_key');
            //判断是否发送过
            if (time() - $send_time < 30) {
                $this->error("30秒内只能发送一次");
            }
            if (empty($send_time)) {
                $time = time();
                Cache::set($data['mobile'] . '-time_key', $time, 30);
            }
            $result = '';
            $this->model->startTrans();
            try {
                $result = $this->model->sendMobile($user_id, $data['mobile'], $data['status']);
                $this->model->commit();
            } catch (Throwable $e) {
                $this->model->rollback();
                $this->error($e->getMessage());
            }
            $this->success('successful', ['list' => $result]);
        }
    }

    //忘记支付密码--重新修改
    public function forgetPayPassword(): void
    {
        $row = $this->model->find($this->auth->id);
        if (!$row) {
            $this->error("当前用户未找到");
        }
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error("参数不能为空");
            }
            if ($data['code'] == "") {
                $this->error("验证码输入为空");
            }
            if ($data['mobile'] !== $row->mobile) {
                $this->error("手机号输入不正确");
            }
            $check_password = $this->model->checkPasswordIsTrue($data['new_pay_password'], $data['confirm_pay_password']);
            if (!$check_password) {
                $this->error("确认密码输入不一致");
            }
            $flag = $this->model->checkCode($row->id, $data['mobile'], $data['code']);
            if ($flag == 0) {
                $this->error("验证码输入不正确");
            }
            if ($flag == 2) {
                $this->error("验证码过期,请重新获取");
            }
            $result = false;
            $this->model->startTrans();
            try {
                if ($flag == 1) {
                    $result = $this->model->payPassword($row->id, $data['new_pay_password']);
                }
                $this->model->commit();
            } catch (Throwable $e) {
                $this->model->rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(('修改密码成功'));
            } else {
                $this->error(('未做任何修改'));
            }
        }
    }


    //修改支付密码
    public function updatePayPassword(): void
    {
        $row = $this->model->find($this->auth->id);
        if (!$row) {
            $this->error("当前用户未找到");
        }
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error("参数不能为空");
            }
            if ($data['pay_password'] == "") {
                $this->error("验证码输入为空");
            }
            $check_password = $this->model->checkPayPassword($row->pay_password, $data['pay_password']);
            if (!$check_password) {
                $this->error("支付密码验证失败,请重新输入");
            }
            $confirm_check_password = $this->model->checkPasswordIsTrue($data['new_pay_password'], $data['confirm_pay_password']);
            if (!$confirm_check_password) {
                $this->error("确认密码输入不一致");
            }
            $result = false;
            $this->model->startTrans();
            try {
                $result = $this->model->payPassword($row->id, $data['new_pay_password']);
                $this->model->commit();
            } catch (Throwable $e) {
                $this->model->rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(('修改密码成功'));
            } else {
                $this->error(('未做任何修改'));
            }
        }
    }

    //获取手机号
    public function getPhoneNumber(): void
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();

            $result = false;
            $result = $this->model->getWeChatPhone($data);
            $this->model->startTrans();
            try {
                $result = $this->model->getWeChatPhone($data);
                $this->model->commit();
            } catch (Throwable $e) {
                $this->model->rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success('', ['mobile' => $result]);
            } else {
                $this->error("获取失败");
            }
        }
    }


    //忘记登录密码--重新修改
    public function forgetPassword(): void
    {

        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error("参数不能为空");
            }
            $row = $this->model->where(['mobile' => $data['mobile']])->find();
            if (!$row) {
                $this->error("当前用户未找到");
            }
            if ($data['code'] == "") {
                $this->error("验证码输入为空");
            }
            $flag = $this->model->checkCode($row->id, $data['mobile'], $data['code']);
            if ($flag == PublicStatus::PUBLIC_STATUS_ZERO) {
                $this->error("验证码输入不正确");
            }
            if ($flag == PublicStatus::PUBLIC_STATUS_TWO) {
                $this->error("验证码过期,请重新获取");
            }
            $check_password = $this->model->checkPasswordIsTrue($data['new_password'], $data['confirm_password']);
            if (!$check_password) {
                $this->error("确认密码输入不一致");
            }
            $result = false;
            $this->model->startTrans();
            try {
                if ($flag == PublicStatus::PUBLIC_STATUS_ONE) {
                    $result = $this->model->resetPassword($row->id, $data['new_password']);
                }
                $this->model->commit();
            } catch (Throwable $e) {
                $this->model->rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(('修改密码成功'));
            } else {
                $this->error(('未做任何修改'));
            }
        }
    }


    //个人中心菜单
    public function userMenuList(): void
    {

        $res[] = [
            'id' => 1,
            'title' => '首页',
            'icon' => 'icon-home-fill',
            'path' => '/userhome',
            'name' => 'userHome',
            'children' => [],
        ];
        $res[] = [
            'id' => 2,
            'title' => '账户管理',
            'icon' => 'icon-settings-fill',
            'path' => '/account_sys',
            'name' => 'account',
            'children' => [
                ['id' => 3, 'title' => '账号密码', 'path' => '/account_sys', 'name' => 'account_sys', 'icon' => 'icon-lock-fill'],
                ['id' => 4, 'title' => '账号余额', 'path' => '/user_balance', 'name' => 'user_balance', 'icon' => 'icon-money-finance-seller-fill']
            ]
        ];
        $res[] = [
            'id' => 5,
            'title' => '订单管理',
            'path' => '/recharge_order',
            'name' => 'recharge_order',
            'icon' => 'icon-order-manage-fill',
            'children' => [
                ['id' => 6, 'title' => '充值订单', 'path' => '/recharge_order', 'name' => 'recharge_order', 'icon' => 'icon-order-fill'],
            ]
        ];
        $res[] = [
            'id' => 7,
            'title' => '下载记录',
            'path' => '/user_dowload',
            'name' => 'user_dowload',
            'icon' => 'icon-catalog-download-fill',
            'children' => [],
        ];
        $res[] = [
            'id' => 8,
            'title' => '素材管理',
            'path' => '/usermaterial',
            'name' => 'userMaterial',
            'icon' => 'icon-product-fill',
            'children' => [
                ['id' => 9, 'title' => '我的收藏', 'path' => '/user_collect', 'name' => 'user_collect',      'icon' => 'icon-follow-fill',],
                ['id' => 10, 'title' => '我的足迹', 'path' => '/user_footprint', 'name' => 'user_collect',      'icon' => 'icon-chengchangzhiyin',],
            ]
        ];
        $res[] = [
            'id' => 11,
            'title' => '消息管理',
            'path' => '/user_message',
            'name' => 'userMessage',
            'icon' => 'icon-message-comments-fill',
            'children' => [],
        ];
        $this->success('', $res);
    }

    //修改用户信息
    public function updateUserInfo(): void
    {
        if ($this->request->isPost()) {
            $data = $this->request->param();
            if (!$data) {
                $this->error("参数不能为空");
            }
            $row = $this->model->where(['mobile' => $data['mobile']])->find();
            if (!$row) {
                $this->error("当前用户未找到");
            }
            $result = false;
            $this->model->startTrans();
            try {
                $result = $this->model->updateUserInfo($row->id, $data);
                $this->model->commit();
            } catch (Throwable $e) {
                $this->model->rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(('修改成功'));
            } else {
                $this->error(('未做任何修改'));
            }
        }
    }


    //设置密码
    public function setPassword(): void
    {

        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error("参数不能为空");
            }
            $model = $this->auth->getUser();
            $flag = $this->model->checkCode($model->id, $model->mobile, $data['code']);
            if ($flag == PublicStatus::PUBLIC_STATUS_ZERO) {
                $this->error("验证码输入不正确");
            }
            if ($flag == PublicStatus::PUBLIC_STATUS_TWO) {
                $this->error("验证码过期,请重新获取");
            }
            $model->startTrans();
            try {
                $model->resetPassword($this->auth->id, $data['password']);
                $model->commit();
            } catch (Throwable $e) {
                $model->rollback();
                $this->error($e->getMessage());
            }
            $this->auth->logout();
            $this->success(('密码设置成功, 请重新登录~'));
        }
    }


    //获取用户的入驻天数
    public function getUserRegDay(): void
    {
        $model = $this->auth->getUser();
        $timestamp1 = strtotime(date('Y-m-d', time()));
        $timestamp2 = strtotime(date('Y-m-d', $model->join_time));
        // 计算两个时间戳之间的秒数差  
        $diffInSeconds = abs($timestamp1 - $timestamp2);
        // 将秒数差转换为天数  
        $diffInDays = ceil($diffInSeconds / (60 * 60 * 24));
        $this->success('', ['day' => intval($diffInDays)]);
    }



    //收藏列表
    public function collectList(): void
    {
        $limit = $this->request->param('limit', 10);
        $map = [];
        if ($this->request->has('title') && !empty($this->request->param('title'))) {
            $map[] = ['title', 'like', '%' . $this->request->param('title') . '%'];
        }
        $where[] = ['user_id', '=', $this->auth->id];
        $res = UserCareProduct::with(['product'=>['nav']])->where($where)->order('create_time desc')->paginate($limit)->each(function ($item, $key) {
            $item['product']['full_url'] = full_url($item['product']['url']);
            return $item;
        });
        $this->success('', [
            'list'  => $res->items(),
            'total' => $res->total(),
        ]);
    }

    //用户足迹
    public function userHistoryAction(): void
    {
        $limit = $this->request->param('limit', 10);
        $page = $this->request->param('page', 1);
        $map = [];
        if ($this->request->has('title') && !empty($this->request->param('title'))) {
            $map[] = ['title', 'like', '%' . $this->request->param('title') . '%'];
        }
        $where[] = ['user_id', '=', $this->auth->id];
        $where[] = ['type', '=', PublicStatus::PUBLIC_STATUS_ONE];
        $res = UserHistory::field('id,user_id,product_id,create_time')->with(['product'=>function($query){
            $query->field('id,title,url');
            return $query;
        }])->where($where)->order('create_time desc')->select();
        $formateResult = [];
        //按照日期分组
        foreach ($res as $k => &$v) {
            $time = date('m-d', strtotime($v['create_time']));
            $arr = explode('-', $time);
            $formateResult[$time]['browseTime'] = reset($arr) . "月" . end($arr) . '日';
            $formateResult[$time]['browseProducts'][] = $v;
        }
        $count = count($formateResult); //总条数

        $start = ($page - 1) * $limit; //偏移量，当前页-1乘以每页显示条数

        $result = array_slice($formateResult, $start, intval($limit));
        $this->success('', [
            'list'   => array_values($result),
            'total'  => $count,
            'remark' => '',
        ]);
    }

    //收藏历史下载
    public function collAndHisAndDowlond(): void
    {
        $type = $this->request->param('type', 'collect');
        switch ($type) {
            case "collect":
                $res = UserCareProduct::with(['product'])->where(['user_id' => $this->auth->id])->order('create_time desc')->limit(20)->select()->each(function ($item, $key) {
                    if ($item->product) {
                        // 动态追加属性，full_url 不会保存在 product 的原始数据中，但在转数组时会包含
                        $item->product->full_url = full_url($item->product->url);
                    } else {
                        // 使用 set 方法设置一个普通的 product 属性
                        $item->set('product', [
                            'full_url' => get_sys_config('defalut_product_img')
                        ]);
                    }
                    return $item;
                })->toArray();
                break;
            case "history":
                $res = UserHistory::with(['product'])->where(['user_id' => $this->auth->id, 'type' => PublicStatus::PUBLIC_STATUS_ONE])->limit(20)->select()->each(function ($item, $key) {
                    if ($item->product) {
                        // 动态追加属性，full_url 不会保存在 product 的原始数据中，但在转数组时会包含
                        $item->product->full_url = full_url($item->product->url);
                    } else {
                        // 使用 set 方法设置一个普通的 product 属性
                        $item->set('product', [
                            'full_url' => get_sys_config('defalut_product_img')
                        ]);
                    }
                    return $item;
                })->toArray();
                break;
            case "dowload":
                $res = UserHistory::with(['product'])->where(['user_id' => $this->auth->id, 'type' => PublicStatus::PUBLIC_STATUS_TWO])->limit(20)->select()->each(function ($item, $key) {
                    if ($item->product) {
                        // 动态追加属性，full_url 不会保存在 product 的原始数据中，但在转数组时会包含
                        $item->product->full_url = full_url($item->product->url);
                    } else {
                        // 使用 set 方法设置一个普通的 product 属性
                        $item->set('product', [
                            'full_url' => get_sys_config('defalut_product_img')
                        ]);
                    }
                    return $item;
                })->toArray();
                break;
            default:
                $res = [];
                break;
        }
        $this->success('', [
            'list'   => $res,
            'remark' => '',
        ]);
    }



    //用户下载记录
    public function userDownloadList(): void
    {
        $limit = $this->request->param('limit', 10);
        $res = UserHistory::with(['product'])->where(['user_id' => $this->auth->id, 'type' => PublicStatus::PUBLIC_STATUS_TWO])->order('create_time desc')->paginate($limit)->each(function ($item, $key) {
            $item['product']['full_url'] = full_url($item['product']['url']);
            return $item;
        });
        $this->success('', [
            'list'   => $res->items(),
            'total'  => $res->total(),
            'remark' => '',
        ]);
    }



    //悬浮按钮
    public function helpCenterBtn(): void
    {

        $res[] = [
            'id' => 1,
            'title' => '客服',
            'type' => 'service',
            'icon' => 'Service',
            'showMenu' => true,
            'children' => [
                ['id' => 2, 'title' => '在线客服','type'=>'dialog','url'=>''],
            ],
        ];
        $res[] = [
            'id' => 3,
            'title' => '帮助中心',
            'type' => 'help',
            'icon' => 'Plus',
            'showMenu' => true,
            'children' => [
                ['id' => 4, 'title' => '反馈及意见','type'=>'dialog','url'=>''],
                ['id' => 5, 'title' => '常见问题','type'=>'url','url'=>'help_center']
            ]
        ];
        $res[] = [
            'id' => 6,
            'title' => '返回顶部',
            'icon' => 'Top',
            'showMenu' => false,
            'type' => 'top',
            'children' => [
                ['id' => 7, 'title' => '返回顶部'],
            ],
        ];
        $this->success('', $res);
    }

    //保存客户申请记录
    public function saveCustomer() : void {
        $customer = new Customer();
        if($this->request->isPost()){
            $data = $this->request->post();
            if (!$data) {
                $this->error("参数不能为空");
            }
            // if(intval($data['subscribe_id']) === PublicStatus::PUBLIC_STATUS_ZERO){
            //     $this->error("请选择您定制的内容");
            // }
            $customer->startTrans();
            try {
                $customer->save($data);
                $customer->commit();
            } catch (Throwable $e) {
                $customer->rollback();
                $this->error($e->getMessage());
            }
            $this->success(('申请提交成功,请耐心等待审核~'));
        }
    }

    
    //验证用户授权码 
    public function verifyUserAuthCode() : void {
        $userCode = $this->request->param('userCode');
        $is_find = $this->model->where('auth_code',$userCode)->find();
        if(!$is_find){
            $this->error("授权码不存在");
        }
        $res = $this->model->userAuthCodeBindIp($is_find['id'],$userCode);
        if(!$res){
            $this->error("该授权码已经绑定,请勿重复绑定");
        }
        $data = ['mobile'=>$is_find['mobile'],'password'=>'YM123456'];
        $this->success('验证通过',$data);
    }
}
